from webob import Response
from webob.exc import HTTPNotFound
from fusion.http.controllers import BaseController
from fusion.db.profile import Profile

class Content(BaseController):
    def index(self, req):
        db = req.environ['fusion.db']
        iid = req.urlvars['fusion.hexlabel']
        path = req.urlvars['fusion.path']
        path = '/'+path

        
        ret = None
        dom_cipher = None
        if req.params.get('auto_crypt'):
            try:
                dom_cipher = db.get_domain_cipher(iid)
            except LookupError:
                assert dom_cipher == None
                pass

        output_type = req.params.get('output')
        if not output_type:
            output_type = 'default'
        
        if output_type == 'json':
            # JSON
            pass
        elif output_type == 'text':
            # TEXT
            try:
                ret = db.get(iid, path, cipher=dom_cipher)
            except Exception, e:
                print "GET_TEXT FAILED (%s).. %s " % (path, e)
        else:
            # DEFAULT
            try:
                ret = db.get(iid, path, cipher=dom_cipher)
            except Exception, e:
                print "GET FAILED (%s).. %s " % (path, e)

        #[TODO: encoding, mimetype?]
        if ret:
            mime_type = self._get_mime_type(path)
            res = Response(content_type=mime_type)
            res.body = ret
            return res
        else:
            return HTTPNotFound()
            
